package com.guodexian.bookman.controller;

import com.guodexian.bookman.entity.User;
import com.guodexian.bookman.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.validation.Valid;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    //转发功能
    @GetMapping("reg")
    public String toReg(User user) {
        return "user/reg";
    }
    @PostMapping("reg")
    public String doReg(@Valid User user, BindingResult result, Model model, @RequestParam("photox") Part part, HttpServletRequest request) throws IOException {
       if (result.hasErrors()){
           return  "user/reg";
       }

        String realPath=request.getServletContext().getRealPath("/upload/");
        String submittedFileName = part.getSubmittedFileName();
        String ext=submittedFileName.substring(submittedFileName.lastIndexOf("."));
        String newFileName= UUID.randomUUID()+ext;
        part.write(realPath+newFileName);
        user.setPhoto(newFileName);
        userService.saveUser(user);
        return "home";
    }
   @GetMapping("/login")
    public String toLogin(User user){
        return "user/login";
    }
    @PostMapping("login")
    public String doLogin(User user){
      User dbUser=userService.findUserByNameAndPwd(user);
      if (dbUser==null){
          return  "user/login";
      }else{
          return "home";
      }
    }

}
